package com.pedro.streamer.service;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.pedro.common.ConnectChecker;
import com.pedro.encoder.input.decoder.AudioDecoderInterface;
import com.pedro.encoder.input.decoder.VideoDecoderInterface;
import com.pedro.library.generic.GenericFromFile;
import com.pedro.library.view.OpenGlView;
import com.pedro.streamer.manager.VideoArrManager;

import java.io.IOException;
import java.util.ArrayList;

public class OpenGLService extends Service implements ConnectChecker,
        VideoDecoderInterface, AudioDecoderInterface {
    private ArrayList<Uri> videoPicArr;
    private String TAG = "com.bmi.OpenGLService";
    private Uri curVideoPath ;
    private Boolean isconnected=false;
    private OpenGlView openGlView;
    private GenericFromFile genericFromFile;
    private int count = 0;
    private String pushUrl="rtmp://127.0.0.1:1935/file/live";
    @Override
    public void onCreate() {
        super.onCreate();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        VideoArrManager.shareInstance(this).bindService(intent);
        return super.onStartCommand(intent, flags, startId);
    }

    private Boolean prepare() throws IOException {
        if (curVideoPath == null) return false;
        boolean result = genericFromFile.prepareVideo(this, curVideoPath);
        if (!result){
            result = genericFromFile.prepareAudio(this, curVideoPath);
        }
        return result;
    }


    public void setVideoPicArr(ArrayList<Uri> videoPicArr) {
        this.videoPicArr = videoPicArr;
    }

    public ArrayList<Uri> getVideoPicArr() {
        return videoPicArr;
    }

    private void startPlayAndPush() throws IOException {
        if (genericFromFile.isRecording() || prepare()) {
//      if (!genericFromFile.isAudioDeviceEnabled) genericFromFile.playAudioDevice()//这不需要播放音频，远端拉流在播放，避免两个播放器都播放音频
            genericFromFile.startStream(pushUrl);

        }
    }

    public void setOpenGlView(OpenGlView openGlView) {
        this.openGlView = openGlView;
        genericFromFile = new GenericFromFile(openGlView, this, this, this);
        genericFromFile.getStreamClient().setReTries(3);//设置重试次数 3次，一般情况下本地除非rtmp端口占用，一般不会连接不上。
        Log.d(TAG, "setOpenGlView: ");
    }

    public GenericFromFile getGenericFromFile() {
        Log.d(TAG, "getGenericFromFile: ");
      return   this.genericFromFile;
    }

    public void setCurVideoPath(Uri curVideoPath) {
        this.curVideoPath = curVideoPath;
    }

    private void stopPlayAndPush(){
//    genericFromFile.stopAudioDevice()//这不需要播放音频，远端拉流在播放，避免两个播放器都播放音频
        if (genericFromFile.isStreaming()) {
            genericFromFile.stopStream();
        }
    }
    public class OpenGLBinder extends Binder {
        private OpenGLService mOpenGLService;
        public OpenGLBinder(OpenGLService openGLService) {
            mOpenGLService = openGLService;
        }

        public void startPlayAndPush(){
            try {
                Log.d(TAG, "startPlayAndPush: ");
                mOpenGLService.startPlayAndPush();
            }catch (Exception e){

            }

        }


        public void stopPlayAndPush(){
            mOpenGLService.stopPlayAndPush();
        }


        public void setOpenGlView(OpenGlView openGlView) {
            mOpenGLService.setOpenGlView(openGlView);
        }

        public GenericFromFile getGenericFromFile() {
          return  mOpenGLService.getGenericFromFile();

        }

        public void setCurVideoPath(Uri curVideoPath) {
            mOpenGLService.setCurVideoPath(curVideoPath);
        }

    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new OpenGLBinder(this);
    }
    @Override
    public void onConnectionStarted(@NonNull String url) {


    }

    @Override
    public void onConnectionSuccess() {
        isconnected=true;
        Log.d(TAG, "Connected Success");
    }

    @Override
    public void onConnectionFailed(@NonNull String reason) {
        if (genericFromFile.getStreamClient().reTry(500, reason, null)) {
            Log.d(TAG, "Retry ");
        } else {
            Log.d(TAG, "Connected fail ");
            genericFromFile.stopStream();

        }

    }

    @Override
    public void onDisconnect() {
        isconnected=false;
        Log.d(TAG, "Connected Disconnect ");
    }

    @Override
    public void onAuthError() {
        genericFromFile.stopStream();
        Log.d(TAG, "onAuthError ");
    }

    @Override
    public void onAuthSuccess() {
        Log.d(TAG, "onAuthSuccess ");
    }

    @Override
    public void onAudioDecoderFinished() {

    }

    @Override
    public void onVideoDecoderFinished() {
        Log.d(TAG, "onVideoDecoderFinished: ");
        openGlView.post(new Runnable() {
            @Override
            public void run() {
                stopPlayAndPush();
            }
        });

        count ++ ;
        if (count >= videoPicArr.size()){
            count = 0;
        }
        curVideoPath = videoPicArr.get(count);
        openGlView.post(new Runnable() {
            @Override
            public void run() {
                try {
                    startPlayAndPush();
                }catch (Exception e){

                }

            }
        });
    }
}
